<template>
  <div class="main-box">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区域 -->
    <el-card>
      <div>
        <el-button type="primary" @click="addRole">添加角色</el-button>
      </div>
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" label="序号" width="100%">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二\三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="info"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="序号" width="100%">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑权限按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRoles(scope.row)"
              >编辑</el-button
            >

            <!-- 删除权限按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteMessageBox(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
          
    </el-card>

    <!-- 修改角色信息 -->
    <el-dialog title="" :visible.sync="editDialogVisible" width="50%">
      <div>
        <el-form ref="form" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="curRoleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="curRoleDesc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="editRolesDialogCancel">取 消</el-button>
        <el-button type="primary" @click="editRolesDialogConfirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配权限对话框展示 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色弹窗 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="width">
      <div>
        <el-form ref="addRoleForm" :model="addRoleForm" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="addRoleDialogCacel">取 消</el-button>
        <el-button type="primary" @click="addRoleDialogConfirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
    data(){
        return {
            roleslist:[],
            // 控制分配权限对话框展示与隐藏
            setRightsDialogVisible:false,
            // 权限列表
            rightslist:[],
            //树形结构展示的字段
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            defKeys:[],
            roleId:'',
            // 控制修改角色对话框的展示与隐藏
            editDialogVisible:false,
            // 当前选中角色
            curRole:{},
            // 当前角色表格数据
            curRoleName:'',
            curRoleDesc:'',
            // 添加角色信息
            addRoleDialogVisible:false,
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
         

         

        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        // 得到角色权限列表
        async getRolesList(){
            const {data:res} =await this.$http.get('roles')
            if(res.meta.status!==200) return this.$message.error('请求角色列表错误')
            this.roleslist = res.data
        },
        // 移除角色权限函数
      async  removeRightById(roles,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该权限?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).catch(err=>err)
            if(confirmResult=='confirm'){
             
             const {data:res} = await this.$http.delete('roles/'+roles.id+'/rights/'+rightId)
             if(res.meta.status!==200) return this.$message.error(res.meta.msg)
             this.$message.success(res.meta.msg)
             roles.children = res.data

            }



        },

        // 展示添加角色权限对话框
       async showSetRightsDialog(role){
            // 获取所有权限列表
        this.roleId = role.id
        const {data:res} = await this.$http.get('rights/tree')
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.rightslist = res.data
       this.getLeafKeys(role,this.defKeys)

        this.setRightsDialogVisible = true
       
  
        },
// 递归获取树形结构的id
        getLeafKeys(node,arr){
            // 如果不包括childre节点，那么就是三级节点
            if(!node.children){
               return arr.push(node.id)

            }

            node.children.forEach(item => {
                this.getLeafKeys(item,arr)
                
            });

        },
// 设置权限对话框关闭
        setRightsDialogClosed(){
            this.defKeys=[]
        },
// 分配权限
       async allotRights(){
            const keys=[
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const{data:res} = await this.$http.post('roles/'+this.roleId+'/rights',{rids:idStr})
            if(res.meta.status!==200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.getRolesList()
            this.setRightsDialogVisible=false

        },
// 编辑角色
        editRoles(role){
            this.editDialogVisible=true
            this.curRole=role
            this.curRoleName = role.roleName
            this.curRoleDesc = role.roleDesc
            
        },


       async editRolesDialogConfirm(){
         const {data:res} = await this.$http.put('roles/'+this.curRole.id,{
             roleDesc:  this.curRoleDesc,
             roleName: this.curRoleName
         })
    
         if(res.meta.status!==200) return this.$message.error("修改角色信息失败")
         this.$message.success('修改角色信息成功')
         this.editDialogVisible =false
         this.getRolesList()
        },
        editRolesDialogCancel(){
            this.curRoleName='',
            this.curRoleDesc='',
            this.editDialogVisible=false
        },
        // 删除角色
       async deleteMessageBox(roleId){
             const confirmResult = await this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(()=>{this.$message.error('取消删除')})        

        if(confirmResult ==='confirm'){
           const {data:res} = await this.$http.delete('roles/'+roleId)
           if(res.meta.status!==200) return this.$$message.error('删除角色失败')
           this.$message.success('删除角色成功')
           this.getRolesList()
            
        }




        },
        // 添加角色
        addRole(){
            this.addRoleDialogVisible=true
        },
      async  addRoleDialogConfirm(){
         const {data:res} = await this.$http.post('roles',this.addRoleForm)
         if(res.meta.status!==201) return this.$message .error('添加角色失败')
         this.$message.success('添加角色成功')
         this.addRoleDialogVisible = false 
         this.getRolesList()
         
        },
        addRoleDialogCacel(){
            this.addRoleForm.roleName=''
            this.addRoleForm.roleDesc=''
            this.addRoleDialogVisible= false
        }




    }

}
</script>



<style scoped>
.el-table th {
  text-align: center;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>